<template>
	<DatePicker
		:key="key"
		v-model="innerValue"
		:type="type"
		placeholder="请选择"
		:picker-options="pickerOptions"
		:format="format"
		:value-format="format"
		:disabled="disabled"
		:clearable="clearable"
		:readonly="computedReadOnly"
		@change="handleChange"
		@blur="onBlur"
	/>
</template>

<script>
import dayjs from 'dayjs';
import {DatePicker} from 'element-ui';

export default {
	name:'McDatePicker',
	components:{
		DatePicker
	},
	props:{
		value:{
			type:[Date, String],
			default:undefined,
		},
		format:{
			type:[Date, String],
			default:'yyyy-MM-dd',
		},
		startTime:{
			type:[Date, String],
			default:undefined,
		},
		endTime:{
			type:[Date, String],
			default:undefined,
		},
		type:{
			type:String,
			default:'date',
		},
		disabled:{
			type:Boolean,
			default:false,
		},
		clearable:{
			type:Boolean,
			default:false,
		},
		readonly:{
			type:Boolean,
			default:false,
		},
	},
	data(){
		return {
			innerValue:'',
			key:Date.now(),
		};
	},
	computed:{
		computedReadOnly(){
			return this.readonly || (this.startTime && this.endTime && this.startTime > this.endTime);
		},
		realStartTime(){
			if(!this.startTime) return null;
			return dayjs(this.startTime, this.format).valueOf();
		},
		realEndTime(){
			if(!this.endTime) return null;
			return dayjs(this.endTime, 'YYYY-MM-DD 00:00:00').valueOf();
		},
		pickerOptions(){
			return {
				disabledDate:(time) => {
					const timeVal = time.getTime();
					if(!this.realStartTime && !this.realEndTime) return false;
					if(this.realStartTime && this.realEndTime){
						return timeVal < this.realStartTime || timeVal > this.realEndTime;
					}
					return this.realEndTime ? timeVal > this.realEndTime : timeVal < this.realStartTime;
				},
			};
		},
	},
	watch:{
		value:{
			handler(val){
				this.innerValue = val;
			},
			immediate:true,
		},
	},
	methods:{
		handleChange(){
			this.$emit('input', this.innerValue);
			this.$emit('change', this.innerValue);
		},
		onBlur(event){
			this.$emit('blur', event);
		},
	},
};
</script>

<style lang="scss" scoped>
.el-picker-panel__link-btn.el-button--text {
    display: none;
}
</style>